//
// Created by 崔世强 on 2018/4/2.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SwiftyJSON

class AddMemberHandler: NoticeHandlerProtocol {
    static let instance = AddMemberHandler()

    private let queue = DispatchQueue(label: "com.tst.db",qos:.background)

    private init() {
    }
    
    private let contactService = ContactService()

    func handler(_ msg: Message) {
        do {
            let db = SQLiteHelper.getDb()
            var needSyncId = [Int]()
            try db.run(transaction: { _ in
                let json = JSON(parseJSON: msg.content ?? "")
                for userIdJson in json["userIds"].arrayValue {
                    let userId = userIdJson.intValue
                    if userId == AppStatusManager.instance.userLoginStatus.1 ?? 0 {
                        try GroupDao.updateKickout(msg.sessionServerId,kickout:false)
                        try SessionDao.update(msg.sessionServerId,deleted: false)
                        let dic:[String:Any] = ["groupId":msg.sessionServerId,"kickout":false]
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNoteChatMsgGroupMemberChange), object: dic)
                    }
                    if let groupMember = try GroupDao.getMemberWithoutDeleted(msg.sessionServerId, userId: userId) {
                        try GroupDao.updateMember(msg.sessionServerId, userId: userId, deleted: false)
                    }else {
                        let groupMember = GroupMember()
                        groupMember.userId = userId
                        groupMember.groupId = msg.sessionServerId
                        try GroupDao.insert(groupMember)
                        needSyncId.append(userId)
                    }
                }
            })

            for userId in needSyncId {
                
                contactService.syncUserInfo(userId,queue:queue)
                
//                IM.request(.getAUserInfo(userId: userId),success: { [unowned self] (json) in
//                    if reqSuccess(json["code"].stringValue) {
//                        do {
//                            let contactJson = JSON(json["res"].stringValue)
//                            let avatar = contactJson["avatar"].string
//                            let name = contactJson["name"].string ?? "\(userId)"
////                            if let contactInDb = try ContactDao.getContact(userId) {
////                                return
////                            }
//                            let contactToSave = Contact()
//                            contactToSave.userId = userId
//                            contactToSave.name = name
//                            contactToSave.avatar = avatar
//                            contactToSave.me = userId == AppStatusManager.instance.userLoginStatus.1 ?? 0
//                            try ContactDao.saveOrUpdateNormalInfo(contact: contactToSave, and: [])
//                        } catch {
//                            print(error)
//                        }
//                    } else {
//                        let msg = json["msg"].stringValue
//                        print(msg)
//                    }
//                    }, error: { (code) in
//                        print("状态异常：\(code)")
//                }) { (error) in
//                    print(error)
//                }
                
            }
            try GroupService().getGroupInfoFromRemote(msg.sessionServerId,queue:queue)
        } catch {
            print(error)
        }
    }

    func show(_ msg: ChatMessage) -> String? {
        do {
            let db = SQLiteHelper.getDb()
            var returnStr = ""
            try db.run(transaction: { _ in
                let manager = try ContactDao.getContact(msg.from)
                let memberOfManager = try GroupDao.getMember(msg.sessionId, userId: msg.from)

                let json = JSON(parseJSON: msg.text ?? "")
                var addMembers = [String]()
                for userIdJson in json["userIds"].arrayValue {
                    let userId = userIdJson.intValue
                    let userContact = try ContactDao.getContact(userId)
                    let member = try GroupDao.getMember(msg.sessionId, userId: userId)
                    var name = userContact?.remarkName ?? member?.nickName ?? userContact?.name ?? ""
                    if userId == AppStatusManager.instance.userLoginStatus.1 ?? 0 {
                        name = "你"
                    }
                    returnStr.append(name)
                    addMembers.append(name)
                }

                var name = manager?.remarkName ?? memberOfManager?.nickName ?? manager?.name
                if msg.isMe {
                    name = "你"
                }
                returnStr = "\(name ?? "管理员" ) 将 \(addMembers) 加入本群"
            })

            return returnStr

        } catch {
            return msg.text
        }
    }
}
